<script setup>
import ArticleList from '@/components/articleList.vue'
import { computed, reactive, ref} from 'vue'
import {useUserStore} from '@/stores/user'
import upImg from '@/components/upImg.vue'
import { postFileApi } from '@/api/file'
const userStore = useUserStore()
const userInfo = ref({})
userInfo.value = userStore.userInfo
import {
    delArticleApi,
    modyfyArticleApi,
    getArticleApi,
    addArticleWatchApi,
    likeArticleApi,
    getCheckedArticleListApi,
    getUserArticleListApi
} from '@/api/article'
import { useRouter,useRoute } from 'vue-router' 
import { postStatus } from '@/utils/globleVar'
import { ElMessage } from 'element-plus'
const router = useRouter()

//用作展示帖子列表
const showArticleList = reactive({
    articleList:[],
    pageInfo:{}
})
//一次请求获取到的帖子列表
const articleList = ref({})

//--------初始化帖子列表-----------
getArticleList(0,userInfo.value.id)
async function getArticleList(page,id){
    try{
        const resp = await getUserArticleListApi(page,id)
        if(resp.data.code === 200){
            if(page === 0){
                showArticleList.articleList = []
            }
            articleList.value = resp.data.data.content
            showArticleList.pageInfo = resp.data.data.page
            articleList.value.forEach(article=>{
                if(article.status === postStatus.rejected){
                    showArticleList.articleList.push(article)
                }
            })
        } 
    }catch(e){
        console.log(e)
    }
}
//---------修改帖子----------------
const showPost = ref()
const showUpdataBox = ref(false)
const onClickEdit = (post)=>{
  showUpdataBox.value = true
  showPost.value = post
}
//移除旧图片
const delImg = (id)=>{
  const imgsUrl = showPost.value.images
  imgsUrl.forEach((img,index)=>{
      if(img.id === id){
          imgsUrl.splice(index,1)
      }
  })
  showPost.value.images = imgsUrl
}
//添加新图片
const imgFile = ref(FileList)
const onUpload = (imgFiles)=>{
    imgFile.value = imgFiles
}
//移除新图片
const removeImg = (id)=>{
  console.log(imgFile.value)
  imgFile.value.forEach((img,index)=>{
      if(img.uid === id){
          imgFile.value.splice(index,1)
      }
  })
}
//取消更新 
const onCancle = ()=>{
  showUpdataBox.value = false

}
//确认更新
const onUpdate = async (imgFiles)=>{
    //构造请求数据
    const updatePostForm={
      id:showPost.value.id,
      title:showPost.value.title,
      content:showPost.value.content,
      images:[],
      status:postStatus.draft
    }
    //处理旧图片 
    const imageUrlArr = showPost.value.images
    imageUrlArr.forEach((oldImg)=>{
      //构造图片信息
      const img = {
        post_id:showPost.value.id,
       image_url:oldImg.imageUrl
      }
      updatePostForm.images.push(img)
    })
    //处理新图片
    try{
      if(imgFile.value.length !== 0){
          const uploadPromises = imgFile.value.map((file) =>
          postFileApi(file).then((respUpImg) => ({
            post_id:showPost.value.id,
            image_url: respUpImg.data.data[0],
          }))
          );
          // 等待所有图片上传完成
          const newImages = await Promise.all(uploadPromises);
          newImages.forEach(img=>{
            updatePostForm.images.push(img)
          })
      }
    }catch(e){
      console.log(e)
      ElMessage.error('上传图片异常')
    }
    //发送更新请求
    try{
        console.log(updatePostForm)
      const resp = await modyfyArticleApi(updatePostForm)
      if(resp.data.code === 200){
        ElMessage.success('文章更新成功，待审核')
        showUpdataBox.value = false
        imgFile.value = []
        getArticleList(0,userInfo.value.id)
      }
    }catch(e){
    ElMessage.error('文章更新异常')
    console.log(e)
    }
}

//获取下一页数据
const getMoreArticle = async ()=>{
    if(showArticleList.pageInfo.totalPages === 1 
    || showArticleList.pageInfo.number+1 >= showArticleList.pageInfo.totalPages){
        return
    }
    getArticleList(showArticleList.pageInfo.number+1,userInfo.value.id)
}
</script>
<template>
    <!-- 帖子更新弹出框 -->
    <el-dialog
      title="修改文章"
      v-model="showUpdataBox">
      <el-form>
          <el-form-item>
              <span>标题:</span>
              <el-input
              clearable
              placeholder="请输标题"
              v-model="showPost.title"
              ></el-input>
          </el-form-item>
          <el-form-item>
              <span>内容:</span>
              <el-input
              clearable
              placeholder="请输入内容"
              v-model="showPost.content"
              ></el-input>
          </el-form-item>
          <div class="imgs" v-for="(img,index) in showPost.images" :key="index">
              <el-icon
              @click="delImg(img.id)"
              ><CloseBold /></el-icon>
              <img class="img" :src="img.imageUrl">
          </div>
          <upImg
          :showConfirm="true"
          @onUpload="onUpload"
          @onUpdate="onUpdate"
          @removeImg="removeImg"
          ></upImg>
          <el-form-item>
               <el-button
               @click="onCancle">
                  取消
              </el-button>
          </el-form-item>
      </el-form> 
    </el-dialog>
     <div class="article-box">
        <ul 
        :infinite-scroll-distance="20"
        v-infinite-scroll="getMoreArticle"
        style="overflow: auto"
        class="article-list">
            <li  v-for="article in showArticleList.articleList" :key="article.id"
            class="articles">
                <!-- 标题 文字内容 -->
                <el-head class="article">
                    <div class="head">
                        <div class="head-left">
                            <el-avatar 
                            @click="onComment(article.id)" 
                            :size="50" 
                            :src="article.user.avatar" />
                        </div>
                        <div class="head-right">
                            <h6 class="username">{{ article.user.username }}</h6>
                            <div class="time">{{ article.createdAt }}</div>
                        </div>
                    </div>
                    <h4 class="title">{{ article.title }}</h4>
                    <span class="content">{{ article.content }}</span>
                </el-head>
                <!-- 图片 -->
                <div class="imgs">
                    <img v-for="img in article.images" :key="img.id"
                    class="img"
                    :src="img.imageUrl">
                </div>
                <!-- 动作 -->
                <div class="modify-button">
                    <el-button
                    @click="onClickEdit(article)" >修改</el-button>
                    
                </div>
            </li>
        </ul>
    </div>
</template>

<style lang="scss" scoped>
.article-box{
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-direction: column;
    .article-list{
        padding-left: 0px;
        height: 76vh;
        width: 100%;
        overflow: scroll;
        list-style: none;
        display: flex;
        align-items: start;
        flex-direction: column;
        justify-content: space-around;
        .articles{
            width:80%;
            margin: 20px ;
            border-bottom-style:solid;
            border-color:var(--el-color-username);
           // background-color: aliceblue;
            border-radius: 10px;
            .article{
                .head{
                    display: flex;
                    align-items: flex-start;
                    justify-content: start;
                    margin: 10px 10px;
                    .head-left{
                        margin: 20px 20px -15px 20px;
                    }
                    .head-right{
                        margin-top: 20px;
                        .username{
                            display: inline;
                            margin: 10px 0px 20px;
                        }
                        .time{
                            margin-top: 10px;
                            font-size: 15px;
                            color: rgb(175, 175, 175);
                        }
                    }
                }
                .title{
                    margin: 15px 30px;
                }
                .content{
                    margin: 15px 30px;
                }
            }
            .imgs{
                display: flex;
                flex-direction: row;
                flex-wrap: wrap;
                margin: 5px 20px;
                .img{
                    width: 200px;
                    height: 200px;
                }
            }
            .modify-button{
                margin: 20px;
                font-size: 14px;
                display: flex;
                flex-direction: row-reverse;
            }
            // .commests{
            //     list-style: none;
            //     .comment{
            //         margin: 10px;
            //     }
            // }
        }
    }
}
//----文章跟新弹出框------
.el-dialog{
    .el-form{
        .el-form-item{

        }
        .imgs{
            .img{
                width: 200px;
                height: 200px;
            }
        }
    }
}
::-webkit-scrollbar{
    display: none;
    background-color: aliceblue;
}
</style>